import { Component, Vue, Watch } from 'vue-property-decorator';
import { Menu, Divider } from 'ant-design-vue';
import * as CommonService from '@/views/common/common-service';

const SubMenu = {
  template: `
      <a-sub-menu :key="menus.id" v-bind="$props" v-on="$listeners">
        <span slot="title">
          <span>{{ menus.label }}</span>
        </span>
        <template v-for="menu in menus.items">
          <a-menu-item v-if="!menu.items" :key="menu.routerLink">
          <router-link :to="menu.routerLink">{{menu.label}}</router-link>
          </a-menu-item>
          <sub-menu v-else :key="menu.id" :menus="menu" />
        </template>
      </a-sub-menu>
    `,
  name: 'SubMenu',
  isSubMenu: true,
  props: {
    // @ts-ignore
    ...Menu.SubMenu.props,
    menus: {
      type: Object,
      default: () => { },
    },
  },
};

@Component({
  components: {
    'a-menu': Menu,
    SubMenu,
    'a-divider': Divider
  }
})
export default class SideBar extends Vue {
  subTitle: string = '';
  sysIcon: string = '';
  menus: Array<any> = [];
  defaultSelectedKeys: any[] = [];
  openKeys: any[] = [];
  customFlag: boolean = false;
  /** 当前选中的路由 */
  selectedKeys: any[] = [];

  @Watch("$route.path")
  onPathChange() {
    let path = this.$route.path;
    const index = path.indexOf(";");
    if (index > -1) {
      path = path.slice(0, index);
    }
    this.selectedKeys = [path];
  }

  created() {
    this.onPathChange();
    let matched = this.$route.matched[1], { name, meta } = matched;
    this.customFlag = !!meta['customFlag'];
    if (this.customFlag) {
      let bizId = this.$route.params.bizId;
      this.loadConfigDetail(bizId);
      this.loadTaskListGroup(bizId);
    } else if (name === 'report-statis') {
      this.listReports(meta.type);
    } else {
      this.getInitSystemByUrl({ url: meta.url });
      this.initsystemresource({ sysId: meta.sysId, resTypes: '', url: meta.url });
    }
  }

  async loadConfigDetail(bizId: string, taskListGroupId = 0) {
    const icon = this.$route.query.iconImage;
    let data = await CommonService.loadConfigDetail({ bizId, taskListGroupId });
    this.subTitle = data.bizName;
    this.getSysIcon(data.bizIcon);
  }

  async loadTaskListGroup(bizId: string) {
    let data = await CommonService.loadTaskListGroup({ bizId });
    this.menus = data;
    this.initDefault(this.menus);
  }

  async listReports(reportTypeId: any) {
    this.menus = await CommonService.listReports({ reportTypeId });
    this.initReportStatis(this.menus);
  }

  async getInitSystemByUrl(params: any) {
    let data = await CommonService.getInitSystemByUrl(params)
    this.subTitle = data.sysName;
    this.getSysIcon(data.iconImage);
  }

  getSysIcon(iconImage?: any) {
    if (iconImage === 'note') {
      iconImage = '';
    }
    let icon = this.$route.query.iconImage as string;
    if (icon) {
      sessionStorage.setItem('sysIcon', icon);
    } else {
      icon = sessionStorage.getItem('sysIcon') || '';
    }
    this.sysIcon = icon || iconImage;
    if (!this.sysIcon) {
      this.sysIcon = 'iconfont-zhifa iconyunhangjiandu';
    } else if (!this.sysIcon.includes('iconfont-zhifa')) {
      this.sysIcon = 'iconfont ' + this.sysIcon;
    }
  }

  async initsystemresource(params: any) {
    let data = await CommonService.initsystemresource(params);
    if (params.url === 'data-bank') {
      this.openKeys.push(data.menus[0].id);
      const sub = await CommonService.getResourceTypes();
      if (sub && sub.length > 0) {
        data.menus[0].items = sub.map((item: any) => {
          return {
            label: item,
            id: item,
            routerLink: data.menus[0].routerLink + '/' + encodeURI(item),
            queryParams: { type: 1 }
          };
        });
        if (params.url === 'data-bank' && !this.$route.params.label) {
          this.$router.replace(data.menus[0].items[0].routerLink);
        }
      }
    }
    this.menus = data.menus;
    this.initDefault(this.menus);
    let resources: any = sessionStorage.getItem('resources');
    if (resources) {
      resources = resources.split(',');
    } else {
      resources = [];
    }
    data.resIds.forEach((id: string) => {
      if (resources.indexOf(String(id)) === -1) {
        resources.push(id);
      }
    })
    sessionStorage.setItem('resources', resources.join(','));
  }


  initDefault(menus: any[]) {
    for (let i = 0, length = menus.length; i < length; i++) {
      if (menus[i].items) {
        this.initDefault(menus[i].items);
      } else if (menus[i].routerLink === this.$route.path) {
        if (menus[i].seniorId) {
          this.openKeys.push(menus[i].seniorId);
        }
        this.defaultSelectedKeys.push(menus[i].id);
        break;
      }
    }
  }

  initReportStatis(menus: any[]) {
    for (let i = 0, length = menus.length; i < length; i++) {
      if (this.defaultSelectedKeys.length > 0) {
        break;
      }
      if (menus[i].items) {
        if (menus[i].seniorId) {
          this.openKeys.push(menus[i].seniorId);
        }
        this.initReportStatis(menus[i].items);
      } else {
        this.openKeys.push(menus[i].seniorId);
        this.defaultSelectedKeys.push(menus[i].id);
        if (this.$route.path !== menus[i].routerLink) {
          this.$router.push(menus[i].routerLink);
        }
        break;
      }
    }
  }
}